package com.luxury;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luxury.activity.SettlementCenterActivity;
import com.luxury.adpter.ProductGridViewAadapter;
import com.luxury.bean.ProductBean;
import com.luxury.r_innerface.InterfaceLuxury;
import com.luxury.utils.GlideImageLoader;
import com.luxury.utils.URLContants;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.onekeyshare.OnekeyShare;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static android.widget.ImageView.ScaleType.CENTER;

public class ProductActivity extends AppCompatActivity {
    public static final String URL = "http://android.secoo.com/appservice/query_goods" + "" +
            ".action?productId=18162603";
    public static final String Share_URL = "http://m.secoo.com/detail/";
    private static final String TAG = "productActivity";
    @BindView(R.id.banner_product)
    Banner banner_product;
    @BindView(R.id.ct_banner)
    CollapsingToolbarLayout ctBanner;
    @BindView(R.id.iv_bag_product)
    ImageView iv_bagProduct;//点击进入购物车
    @BindView(R.id.iv_collect_product)
    ImageView ivCollectProduct;//点击收藏
    @BindView(R.id.iv_share_product)
    ImageView iv_shareProduct;//点击分享
    @BindView(R.id.iv_service_product)
    ImageView iv_serviceProduct;//点击进入客服
    @BindView(R.id.tv_name_product)
    TextView tv_nameProduct;//显示产品名字
    @BindView(R.id.tv_price_product)
    TextView tv_priceProduct;
    @BindView(R.id.tv_areaOrTime_product)
    TextView tv_areaOrTimeProduct;//显示从哪发货 发货时间
    @BindView(R.id.rLayout_product_num1Last)
    RelativeLayout rLayout_ProductNum1Last;//如果库存少于10  布局最右边提醒
    @BindView(R.id.tv_carriage_product)
    TextView tv_CarriageProduct;//显示寺库是否承担运费
    @BindView(R.id.gv_num2_2_product)
    GridView gv_Num22Product;//显示正品保证 权威鉴定 七天退货这些东西  是一个
    @BindView(R.id.tv_detail_product)
    TextView tv_DetailProduct;//商品详情
    @BindView(R.id.iv_detail_product)
    ImageView iv_DetailProduct;//点击展示或隐藏商品详情的图的布局
    @BindView(R.id.layout_detail_product)
    LinearLayout layout_DetailProduct;//动态加载商品详情图片的布局
    @BindView(R.id.tv_params_product)
    TextView tv_ParamsProduct;//商品参数
    @BindView(R.id.layout_params_product)
    LinearLayout layout_ParamsProduct;//动态展示产品参数的布局
    @BindView(R.id.tv_change_product)
    TextView tv_ChangeProduct;//保养说明/品牌简介  根据字符串判断
    @BindView(R.id.iv_change_product)
    ImageView iv_ChangeProduct;//点击展示或者隐藏保养说明/品牌简介的布局
    @BindView(R.id.layout_change_product)
    LinearLayout layout_ChangeProduct;//动态加载保养说明/品牌简介的布局
    @BindView(R.id.layout_product)
    LinearLayout layout_Product;
    @BindView(R.id.btn_selled_product)
    Button btn_SelledProduct;//售罄的按钮  如果库存为0  展示这个button
    @BindView(R.id.btn_bag_product)
    Button btn_BagProduct;//加入购物袋  点击选择之后 回来变成去结算
    @BindView(R.id.btn_buy_product)
    Button btn_BuyProduct;//立即购买
    @BindView(R.id.layout_selling_product)
    LinearLayout layout_SellingProduct;
    @BindView(R.id.layout_module2_product)
    LinearLayout layout_Module2Product;
    @BindView(R.id.rlayout_change_product)
    RelativeLayout rlayout_ChangeProduct;
    @BindView(R.id.rlayout_sell_product)
    RelativeLayout rlayoutSellProduct;
    @BindView(R.id.iv_includeBuyProduct)
    ImageView iv_IncludeBuyProduct;//立即购买的商品展示
    @BindView(R.id.tv_price_includeBuyProduct)
    TextView tv_PriceIncludeBuyProduct;//立即购买价格展示
    @BindView(R.id.tv_down_includBuyProduct)
    TextView tv_DownIncludBuyProduct;//立即购买  减按钮
    @BindView(R.id.tv_size_includBuyProduct)
    TextView tv_SizeIncludBuyProduct;//立即购买量
    @BindView(R.id.tv_up_includBuyProduct)
    TextView tv_UpIncludBuyProduct;//立即购买加按钮
    @BindView(R.id.rlayout_buy_product)
    RelativeLayout rlayout_BuyProduct;//点击加入购物车或者立即购买弹出的页面
    @BindView(R.id.btn_include_sure)
    Button btn_IncludeSure;
    String mImgHead,mId= "";//购买或者加入购物车  显示图片的图片网址
    @BindView(R.id.colayout_productActivity)
    CoordinatorLayout colayou_tProductActivity;
    @BindView(R.id.tv_bagSize_buyProduct)
    TextView tv_BagSizeBuyProduct;//小红点 显示购物车数量的
    @BindView(R.id.tv_inventory_includeBuyProduct)
    TextView tv_InventoryIncludeBuyProduct;//库存
    private int mSize = 1;//显示的购买数量
    boolean isLogined = false;//用来记录是否登陆
    //    @BindView(R.id.btn_include_buynow)
//    Button btnIncludeBuynow;
    private Context mContext = this;
    private ProductBean.RpResultBean mRp_result;
    private List<String> mList_bannerImg = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);
        ButterKnife.bind(this);
//        rlayout_BuyProduct.getVisibility()
//        mImgHead = getIntent().getStringExtra("imgHead");
        mId= getIntent().getStringExtra("productId");
        initData();

    }

    private void initData() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(URLContants.ANDROID_URL)
                .addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory
                        (RxJavaCallAdapterFactory.create()).build();
        InterfaceLuxury interfaceLuxury = retrofit.create(InterfaceLuxury.class);
        Observable<ProductBean> productBean = interfaceLuxury.getProductBean(mId);
        Log.i(TAG, "webView传过来的id--->>"+mId);
        productBean.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Action1<ProductBean>() {
            @Override
            public void call(ProductBean productBean) {
                mRp_result = productBean.getRp_result();
                //判断是哪个按钮
                if (mRp_result.getInventorySize() == 0) {
                    btn_SelledProduct.setVisibility(View.VISIBLE);
                    layout_SellingProduct.setVisibility(View.GONE);
                } else {
                    btn_SelledProduct.setVisibility(View.GONE);
                    layout_SellingProduct.setVisibility(View.VISIBLE);
                }
//                设置 图片展示
                List<String> showPicture = mRp_result.getShowPicture();

                for (int i = 0; i < showPicture.size(); i++) {
                    mList_bannerImg.add("http://pic11.secooimg.com/product/500/500/" + showPicture
                            .get(i));
                    Log.i("TAG", "展示图片:---->>" + "http://pic11.secooimg.com/product/300/300/" +
                            showPicture.get(i));
                }
                //给banner设置样式
                banner_product.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                //设置图片加载器
                banner_product.setImageLoader(new GlideImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        super.displayImage(context, path, imageView);
//                        ???
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200);
                        Log.i(TAG, "设置imgview长和宽");
                        lp.gravity = Gravity.CENTER;
                        imageView.setLayoutParams(lp);
                        Log.i(TAG, "设置imgview长和宽完毕 ");
                        imageView.setScaleType(CENTER);
                    }
                });

                //设置图片集合
                banner_product.setImages(mList_bannerImg);
                //设置title集合
//                banner_product.setBannerTitles(list_bannerTiele);
                //设置banner动画效果
                banner_product.setBannerAnimation(Transformer.DepthPage);
                //设置自动轮播，默认为true
                banner_product.isAutoPlay(false);
                //设置指示器位置（当banner模式中有指示器时）
                banner_product.setIndicatorGravity(BannerConfig.CENTER);
                //banner设置方法全部调用完毕时最后调用
                banner_product.start();

                //设置第一模块
                String productName = mRp_result.getProductName();//商品名
                int refPrice = mRp_result.getRefPrice();//价钱
                String descriptionDelivery = mRp_result.getDescriptionDelivery();//发货时间
                tv_nameProduct.setText(productName);
                tv_priceProduct.setText("￥" + refPrice);
                tv_areaOrTimeProduct.setText("发货时间:" + descriptionDelivery);
                //设置第二模块
                int carriage = mRp_result.getCarriage();
                if (carriage == 0) {
                    tv_CarriageProduct.setText("寺库承担运费");
                } else {
                    tv_CarriageProduct.setText("运费:" + carriage + "元");
                }
//                        第二模块第二行
                List<String> list_22 = new ArrayList<String>();
                if (mRp_result.getCod() == 0) {
                    list_22.add("正品保证");
                    list_22.add("权威鉴定");
                }
                ProductGridViewAadapter p_gvAdapter = new ProductGridViewAadapter(mContext,
                        list_22);
                gv_Num22Product.setAdapter(p_gvAdapter);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup
                        .LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.setMargins(10, 5, 5, 5);
                //第二模块第三行
                if (mRp_result.getDownPayment() == 1) {
                    TextView tv_downpayment = new TextView(mContext);
                    tv_downpayment.setText("本商品不支持分期付款");
                    tv_downpayment.setLayoutParams(lp);
                    layout_Module2Product.addView(tv_downpayment);
                }
                if (mRp_result.getSellStatus() == 1) {
                    TextView tv_sellstatus = new TextView(mContext);
                    tv_sellstatus.setText("本商品不支持货到付款");
                    tv_sellstatus.setLayoutParams(lp);
                    layout_Module2Product.addView(tv_sellstatus);
                }
                //第三行 商品详情页面
                List<ProductBean.RpResultBean.DetailDescBean> list_detailDesc = mRp_result
                        .getDetailDesc();
                final ImageView[] iv_detials = new ImageView[list_detailDesc.size()];
//                        layout_DetailProduct.removeAllViews();
                for (int i = 0; i < list_detailDesc.size(); i++) {
                    iv_detials[i] = new ImageView(mContext);
                    Glide.with(mContext).load(list_detailDesc.get(i).getUrl()).into(iv_detials[i]);
                    layout_DetailProduct.addView(iv_detials[i]);
                }
                //给第三模块商品详情页面>设置点击事件
                iv_DetailProduct.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (layout_DetailProduct.getVisibility() == View.VISIBLE) {
                            layout_DetailProduct.setVisibility(View.GONE);
                            iv_DetailProduct.setRotation(90);
                        } else {
                            layout_DetailProduct.setVisibility(View.VISIBLE);
                            iv_DetailProduct.setRotation(0);
                        }
                    }
                });
                //第四模块商品参数
                List<ProductBean.RpResultBean.ProductExtraPpropertysBean> list_params =
                        mRp_result.getProductExtraPpropertys();
                TextView[] tv_params = new TextView[list_params.size()];
                for (int i = 0; i < list_params.size(); i++) {
                    tv_params[i] = new TextView(mContext);
                    tv_params[i].setLayoutParams(lp);
                    tv_params[i].setText(list_params.get(i).getPropertyName() + ": " +
                            list_params.get(i).getPropertyValue());
                    layout_ParamsProduct.addView(tv_params[i]);
                }
                //第五模块 品牌故事或者是保养说明
                List<String> list_brandStory = mRp_result.getBrandStory();
                if (list_brandStory.size() == 0) {
                    tv_ChangeProduct.setText("保养说明");
                    List<String> list_upkeep = mRp_result.getUpkeep();
                    ImageView[] iv_keep = new ImageView[list_upkeep.size()];
                    for (int i = 0; i < list_upkeep.size(); i++) {
                        iv_keep[i] = new ImageView(mContext);
                        Glide.with(mContext).load(list_upkeep.get(i)).into(iv_keep[i]);
                        layout_ChangeProduct.addView(iv_keep[i]);
                    }
                } else {
                    tv_ChangeProduct.setText("品牌故事");
                    String image = mRp_result.getBrandInfo().getImage();
                    String title = mRp_result.getBrandInfo().getTitle();
                    String content = mRp_result.getBrandInfo().getContent();
                    ImageView iv_brand = new ImageView(mContext);
                    Glide.with(mContext).load(image).into(iv_brand);
                    TextView tv_title = new TextView(mContext);
                    TextView tv_content = new TextView(mContext);
                    tv_title.setText(title);
                    tv_title.setGravity(Gravity.CENTER);
                    tv_title.setTextSize(25);
                    tv_content.setText(content);
                    layout_ChangeProduct.addView(iv_brand);
                    layout_ChangeProduct.addView(tv_title);
                    layout_ChangeProduct.addView(tv_content);
                }
                iv_ChangeProduct.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup
                                .LayoutParams.MATCH_PARENT, 30);
                        if (layout_ChangeProduct.getVisibility() == View.VISIBLE) {
                            layout_ChangeProduct.setVisibility(View.GONE);
                            lp.setMargins(0,0,0,150);

                            iv_ChangeProduct.setRotation(90);
                        } else {
                            layout_ChangeProduct.setVisibility(View.VISIBLE);
                            iv_ChangeProduct.setRotation(0);
                            lp.setMargins(0,0,0,0);
                        }
                        rlayout_ChangeProduct.setLayoutParams(lp);
                    }
                });

            }
        });
    }

    //    点击添加购物车或者立即购买
    public void onSelling(View view) {
        rlayout_BuyProduct.setVisibility(View.VISIBLE);
        rlayout_BuyProduct.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim
                .translate_buyproduct));
        Glide.with(mContext).load(mList_bannerImg.get(0)).into(iv_IncludeBuyProduct);
        tv_PriceIncludeBuyProduct.setText("￥" + mRp_result.getSecooPrice());//显示价格
        tv_InventoryIncludeBuyProduct.setText("库存" + mRp_result.getInventorySize() + "件");//显示库存;
        rlayout_BuyProduct.setBackgroundDrawable(getResources().getDrawable(R.drawable
                .sellingproduct_banckground));
        switch (view.getId()) {
            //加入购物车
            case R.id.btn_bag_product:
                btn_IncludeSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //得到购物车数量  bagSize
                        tv_BagSizeBuyProduct.setVisibility(View.VISIBLE);
                        tv_BagSizeBuyProduct.setText(mSize + "");//应该是bagSize+msize
                        //买东西的布局消失
                        rlayout_BuyProduct.startAnimation(AnimationUtils.loadAnimation(mContext,
                                R.anim.translate_buyproduct_gone));
                        rlayout_BuyProduct.setBackgroundColor(Color.TRANSPARENT);
                        rlayout_BuyProduct.setVisibility(View.GONE);

                    }
                });
                break;
            //立刻购买
            case R.id.btn_buy_product:
                //买东西的布局消失
                btn_IncludeSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        rlayout_BuyProduct.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim
                                .translate_buyproduct_gone));
                        rlayout_BuyProduct.setBackgroundColor(Color.TRANSPARENT);
                        rlayout_BuyProduct.setVisibility(View.GONE);
                        //判断是否登陆
                        isLogined=true;//先让他登陆-->假数据
                        if (isLogined){
                            Intent intent = new Intent(mContext,SettlementCenterActivity.class);
                            //携带参数 mImgHead 图片  购买数量mSize 尺码 颜色  金额  名字title 是否能用y
                            startActivity(intent);
                        }
                    }
                });
              break;
        }
    }

    public void onSizeChange(View view) {
        mSize = Integer.parseInt(tv_SizeIncludBuyProduct.getText().toString() + "") + 0;
        //表示客户购买的数量
        switch (view.getId()) {
            //数量减1
            case R.id.tv_down_includBuyProduct:
                //点击数量减少  当数量为1时候  不能点击
                if (mSize > 1 && mSize <= mRp_result.getInventorySize()) {
                    mSize--;
                    tv_SizeIncludBuyProduct.setText("" + mSize);
                    tv_DownIncludBuyProduct.setTextColor(Color.rgb(0, 0, 0));
                    tv_UpIncludBuyProduct.setTextColor(Color.rgb(0, 0, 0));
                    if (mSize == 1) {
                        tv_DownIncludBuyProduct.setTextColor(Color.argb(8, 0, 8, 0));
                    }

                } else {
                    tv_DownIncludBuyProduct.setTextColor(Color.argb(8, 0, 8, 0));
                }
                break;
            //数量加1
            case R.id.tv_up_includBuyProduct:
                //点击数量增加  当数量>库存 不能点击
                int inventorySize = mRp_result.getInventorySize();
                Log.i(TAG, "库存>>>" + inventorySize);
                if (mSize >= 1 && mSize < mRp_result.getInventorySize()) {
                    mSize++;
                    tv_SizeIncludBuyProduct.setText("" + mSize);
                    tv_DownIncludBuyProduct.setTextColor(Color.rgb(0, 0, 0));
                    tv_UpIncludBuyProduct.setTextColor(Color.rgb(0, 0, 0));
                    if (mSize == mRp_result.getInventorySize()) {
                        tv_UpIncludBuyProduct.setTextColor(Color.argb(8, 0, 8, 0));
                    }
                } else {
                    tv_UpIncludBuyProduct.setTextColor(Color.argb(8, 0, 8, 0));
                }
                break;
        }

    }

    public void closeSure(View view) {
        //点击关闭选择数量的界面
        rlayout_BuyProduct.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim
                .translate_buyproduct_gone));
        rlayout_BuyProduct.setBackgroundColor(Color.TRANSPARENT);
        rlayout_BuyProduct.setVisibility(View.GONE);

    }

    public void onBack(View view) {
        finish();
    }
//点击进行分享
    public void onShare(View view) {
        //1.创建一键分享对象
        OnekeyShare share = new OnekeyShare();
        share.disableSSOWhenAuthorize();//关闭sso授权
        //设置一键分享的内容
        share.setText("我在寺库发现了仅售￥"+mRp_result.getSecooPrice()+"的"+mRp_result.getProductType()+ Share_URL+mId);
        share.show(mContext);
    }
}
